package com.iias.communication.server;

import com.iias.common.util.log.LogUtils;
import com.iias.communication.business.BusinessActuator;
import com.iias.communication.interfaces.ServerConnectionHandler;
import com.iias.communication.packet.ProPacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;

/**
 * 服务端处理
 */
public class TcpServerHandler extends ChannelInboundHandlerAdapter {

    private final static Logger log = LogUtils.getLogger();

    ServerConnectionHandler connectionHandler;


    public TcpServerHandler(ServerConnectionHandler connectionHandler) {
        this.connectionHandler = connectionHandler;
    }

    /**
     * 读取数据
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("channelRead");
        if (msg instanceof ProPacket){
            BusinessActuator.actuator(ctx.channel(), (ProPacket) msg);
        }
//        super.channelRead(ctx, msg);
    }

    /**
     * 检测是否活动
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx ) throws Exception {
        super.channelActive(ctx);
        if (connectionHandler!=null)connectionHandler.clientChannel(ctx.channel());

    }

    /**
     * 读取完成
     * @param ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx ) throws Exception {
//        System.out.println("channelReadComplete");
        super.channelReadComplete(ctx);
        if (connectionHandler!=null)connectionHandler.clientDisconnect(ctx.channel());
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        super.exceptionCaught(ctx, cause);
    }

}
